package com.qf.ability.resources.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import jdk.nashorn.internal.scripts.JS;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/res/img")
public class ImgResourcesController {

    @Value("${uploader.img}")
    private String imgUploaderPath;

    @RequestMapping("/wangeditor/uploader")
    public String wangEditorImgUploderPath(MultipartFile file){
        File filePath = new File(imgUploaderPath);
        if (!filePath.exists()){
            filePath.mkdirs();
        }

        //创建文件名称
        String fileName = UUID.randomUUID().toString();

        //上传
        try(
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(new File(filePath,fileName));
        ) {
            IOUtils.copy(in,out);
        } catch (IOException e) {
            e.printStackTrace();
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errno",0);
        JSONObject sJsonObject = new JSONObject();
        sJsonObject.put("url","http://localhost/res/img/get?fileName=" + fileName);
        jsonObject.put("data",sJsonObject);

        return jsonObject.toJSONString();
    }

    /**
     * 点击图片上传
     * @param file
     * @return
     */
    @RequestMapping("/uploader")
    public R uploader(MultipartFile file){
        File filePath = new File(imgUploaderPath);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        //创建文件名称
        String fileName = UUID.randomUUID().toString();

        //上传
        try(
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(new File(filePath,fileName));
          ){
            IOUtils.copy(in,out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Rs.create(fileName);
    }

    /**
     * 根据名字获取图片
     */
    @RequestMapping("/get")
    public void getImg(String fileName, HttpServletResponse response){
        try(
                InputStream in = new FileInputStream(new File(imgUploaderPath,fileName));
                ServletOutputStream out =  response.getOutputStream();
        ){
            IOUtils.copy(in,out);
            } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
